package com.czl.module_service.fragment.purchase

import android.text.TextUtils
import android.util.Log
import android.widget.ArrayAdapter
import androidx.appcompat.widget.AppCompatAutoCompleteTextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LogUtils
import com.czl.base.base.BaseFragment
import com.czl.base.config.AppConstants
import com.czl.base.data.bean.tengyun.*
import com.czl.base.event.LiveBusCenter
import com.czl.base.util.ChoiceImgHelper
import com.czl.module_service.BR
import com.czl.module_service.R
import com.czl.module_service.adapter.PurchaseApplyAddAdapter
import com.czl.module_service.databinding.*
import com.czl.module_service.view.ListSheetDialogFragment
import com.czl.module_service.viewmodel.PurchaseApplyAddViewModel
import com.czl.module_service.viewmodel.PurchaseApplyAddViewModel.Companion.ADAPTER_IMG

@Route(path = AppConstants.Router.Service.F_SERVICE_PURCHASE_APPLY_ADD)
class PurchaseApplyAddFragment : BaseFragment<FragmentPurchaseApplyAddBinding, PurchaseApplyAddViewModel>() {

    val list : MutableList<PurchaseOrderBean> = arrayListOf()
    private val ownerCompanyList: MutableList<CompanyBean> = arrayListOf()
    private val ownerCompanyNameList: MutableList<String> = arrayListOf()
    private val ownerProjectNameList: MutableList<String> = arrayListOf()

    private lateinit var appCompatAutoCompleteTextView: AppCompatAutoCompleteTextView

    private val footerBinding: FragmentPurchaseApplyAddFooterBinding by lazy  {
        FragmentPurchaseApplyAddFooterBinding.inflate(layoutInflater).apply {

        }
    }

    override fun initContentView(): Int {
        return R.layout.fragment_purchase_apply_add
    }

    private val mAdapter: PurchaseApplyAddAdapter by lazy {
        PurchaseApplyAddAdapter(this) {
            val data = mAdapter.data
            var total = 0
            var totalPrice = 0.00
            data.forEach {
                val count = it.purchaseCount
                var num = 0
                if (!TextUtils.isEmpty(count)) {
                    num = count?.toInt()!!
                    total += count.toInt()!!
                }
                val price = it.price
                if (!TextUtils.isEmpty(price)) {
                    totalPrice += num * (price?.toDouble()!!)
                }
                Log.e("PurchaseFragment", "count = &&$count")
            }
            viewModel.totalCount.set(total.toString())
            viewModel.totalPrice.set(String.format("%.2f",totalPrice))
        }.apply {
            val headerBinding = FragmentPurchaseApplyAddHeaderBinding.inflate(layoutInflater)
            headerBinding.setVariable(initVariableId(), viewModel)
            addHeaderView(headerBinding.root)
            footerBinding.setVariable(initVariableId(), viewModel)
            addFooterView(footerBinding.root)
        }
    }

    override fun initVariableId(): Int {
        return BR.viewModel
    }

    override fun useBaseLayout(): Boolean {
        return false
    }

    override fun initData() {
        super.initData()
        initAdapter()
        viewModel.initData()
        viewModel.getSortList()
        viewModel.getCompanyList()
        viewModel.getIdByNeighNo()
//        viewModel.getRoleProcessList()
        viewModel.adapter = mAdapter
    }

    private fun initAdapter() {
        binding.recyclerView.run {
            adapter = mAdapter
        }
    }

    override fun initViewObservable() {
        LiveBusCenter.observeAddPurchaseSortEvent(this, {
            LogUtils.e("----->" + it.bean)
            if (it.bean != null) {
                // 选中的物品添加
                val index = mAdapter.position - 1
                list[index] = it.bean!!
                viewModel.list = list
                mAdapter.setList(list)
            }
        })
        viewModel.uc.loadCompleteEvent.observe(this, { data ->
            list.add(data[0])
            viewModel.list = list
            LogUtils.e("----->" + list.size)
            if (viewModel.isFirst) {
                mAdapter.isDel = true
                mAdapter.addData(PurchaseOrderBean())
            } else {
                mAdapter.setList(list)
            }
        })
        viewModel.uc.roleCompleteEvent.observe(this, { data ->
            if (data.isNotEmpty()) {
                viewModel.businessType = 0
                footerBinding.btnCommit.text = "提交审批"
            } else {
                viewModel.businessType = 1
                footerBinding.btnCommit.text = "提交"
            }
        })
        viewModel.uc.choiceFacilityTypeEvent.observe(this, {
            val list = mutableListOf("计划外采购", "计划内采购", "计划内紧急采购")
            ListSheetDialogFragment.showBottomSheet(
                parentFragmentManager,
                list,
                block = {
                    viewModel.purchaseTypeName.set(list[it])
                    viewModel.entityBean.purchaseType = it
                }
            )
        })
        viewModel.uc.choiceOwnerCompanyListEvent.observe(this, {
            if (it.list != null) {
                ownerCompanyList.clear()
                ownerCompanyList.addAll(it.list!!)
                for (bean in ownerCompanyList){
                    ownerCompanyNameList.add(bean.companyShortName!!)
                }
            }
        })
        viewModel.uc.choiceOwnerCompanyEvent.observe(this, {
            ListSheetDialogFragment.showBottomSheet(
                parentFragmentManager,
                ownerCompanyNameList,
                block = {
                    viewModel.companyName.set(ownerCompanyNameList[it])
                    val comBean = ownerCompanyList[it]
                    viewModel.entityBean.parentCompanyId = comBean.companyId
                }
            )
        })
        viewModel.uc.choiceOwnerProjectEvent.observe(this, {
            for (bean in viewModel.projectList){
                ownerProjectNameList.add(bean.areaName)
            }
            ListSheetDialogFragment.showBottomSheet(
                parentFragmentManager,
                ownerProjectNameList,
                block = {
                    viewModel.projectName.set(ownerProjectNameList[it])
                    val comBean = viewModel.projectList[it]
                    viewModel.entityBean.projectId = comBean.areaId.toInt()
                }
            )
        })
        viewModel.uc.clearFacilityListEvent.observe(this, {
            viewModel.list.clear()
            viewModel.applicaitonName.set("")
            viewModel.applyComment.set("")
            viewModel.fileParamUrl.set("")
            val list1 : MutableList<PurchaseOrderBean> = arrayListOf()
            list1.add(PurchaseOrderBean())
            mAdapter.setList(list1)
            mAdapter.position = 0
            mAdapter.model = viewModel
        })
        // viewModel中选择附件
        viewModel.uc.choiceImgEvent.observe(this, {
            ChoiceImgHelper.ChoiceImg(this,
                { result -> result[0]?.let { t -> viewModel.uploadHeadImg(t.compressPath, it) } },
                {})
        })
        // adapter中选择附件
        viewModel.uc.choiceAdapterFileEvent.observe(this, {
            val bean = mAdapter.data[mAdapter.position - 1]
            bean.fileUrl = it.url
            val fileBean = FileBean()
            fileBean.name = it.name
            fileBean.fileName = it.name
            fileBean.url = it.url
            fileBean.fileUrl = it.url
            fileBean.userName = viewModel.model.getLoginName()
            fileBean.tname = viewModel.model.getLoginName()
            val list :  MutableList<FileBean> = arrayListOf()
            list.add(fileBean)
            bean.fileList = list
            mAdapter.setData(mAdapter.position - 1, bean)
        })
        // 低值易耗查所有物品
        viewModel.uc.allSortBeanCompleteEvent.observe(this, {
            val arr = arrayOf("北京站", "北京西站", "北京南站")
            val arrayAdapter =
                ArrayAdapter<String>(requireContext(), android.R.layout.simple_expandable_list_item_1, arr)
            appCompatAutoCompleteTextView.setAdapter(arrayAdapter)
            appCompatAutoCompleteTextView.showDropDown()
        })
    }

    fun choiceAssetTypeEvent() {
        val list = mutableListOf("固定资产", "低值易耗")
        ListSheetDialogFragment.showBottomSheet(
            parentFragmentManager,
            list,
            block = {
                val bean = mAdapter.data[mAdapter.position - 1]
                bean.assetTypeName = list[it]
                bean.assetType = it
                mAdapter.setData(mAdapter.position - 1, bean)
            }
        )
    }

    fun choicePurchaseNameEvent() {
        appCompatAutoCompleteTextView = view?.findViewById(R.id.appCompatAutoCompleteTextView)!!
        viewModel.getSortAllList()
    }

    fun deleteList(purchaseOrderBean: PurchaseOrderBean) {
        list.removeAt(purchaseOrderBean.position!! - 1)
        if (list.size == 1) {
            mAdapter.isDel = false
        }
    }

    fun uploadFile() {
        ChoiceImgHelper.ChoiceImg(this,
            { result -> result[0]?.let { t -> viewModel.uploadHeadImg(t.compressPath, ADAPTER_IMG) } },
            {})
    }
}